<template>
  <div class="guide-refunds-page">
    <div class="page-header mb-6">
      <div class="flex items-center justify-between">
        <h2 class="text-2xl font-bold text-gray-900 dark:text-white">
          退款仲裁
        </h2>
        <div class="flex items-center space-x-2">
          <el-button @click="handleExport">
            <el-icon class="mr-1"><Download /></el-icon>导出数据
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm mb-6">
      <div class="flex flex-wrap gap-4 mb-4">
        <el-input
          v-model="searchForm.keyword"
          placeholder="搜索订单号/导游姓名/用户姓名"
          class="!w-64"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select
          v-model="searchForm.status"
          placeholder="退款状态"
          clearable
          class="!w-32"
        >
          <el-option label="全部" value="" />
          <el-option label="待处理" value="pending" />
          <el-option label="已通过" value="approved" />
          <el-option label="已拒绝" value="rejected" />
          <el-option label="已退款" value="refunded" />
        </el-select>

        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          class="!w-80"
        />

        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 退款列表 -->
    <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="待处理" name="pending">
          <template #label>
            待处理
            <el-badge
              v-if="tabCounts.pending"
              :value="tabCounts.pending"
              class="ml-2"
              type="danger"
            />
          </template>
        </el-tab-pane>
        <el-tab-pane label="已通过" name="approved">
          <template #label>
            已通过
            <el-badge
              v-if="tabCounts.approved"
              :value="tabCounts.approved"
              class="ml-2"
              type="success"
            />
          </template>
        </el-tab-pane>
        <el-tab-pane label="已拒绝" name="rejected">
          <template #label>
            已拒绝
            <el-badge
              v-if="tabCounts.rejected"
              :value="tabCounts.rejected"
              class="ml-2"
              type="info"
            />
          </template>
        </el-tab-pane>
        <el-tab-pane label="已退款" name="refunded">
          <template #label>
            已退款
            <el-badge
              v-if="tabCounts.refunded"
              :value="tabCounts.refunded"
              class="ml-2"
              type="primary"
            />
          </template>
        </el-tab-pane>
      </el-tabs>

      <el-table
        v-loading="loading"
        :data="refundsList"
        border
        style="width: 100%"
        row-key="id"
      >
        <el-table-column label="退款信息" min-width="200">
          <template #default="{ row }">
            <div class="space-y-1">
              <div class="text-sm font-medium">
                退款单号：{{ row.refundNo }}
              </div>
              <div class="text-sm text-gray-500">订单号：{{ row.orderNo }}</div>
              <div class="text-sm text-gray-500">
                申请时间：{{ formatDateTime(row.applyTime) }}
              </div>
              <div class="flex items-center mt-1">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="导游信息" min-width="200">
          <template #default="{ row }">
            <div class="flex items-center space-x-3">
              <el-avatar :size="40" :src="row.guide.avatar" />
              <div>
                <div class="text-sm font-medium">{{ row.guide.name }}</div>
                <div class="text-xs text-gray-500">ID: {{ row.guide.id }}</div>
                <div class="text-xs text-gray-500">
                  电话: {{ row.guide.phone }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="用户信息" min-width="200">
          <template #default="{ row }">
            <div class="flex items-center space-x-3">
              <el-avatar :size="40" :src="row.user.avatar" />
              <div>
                <div class="text-sm font-medium">{{ row.user.name }}</div>
                <div class="text-xs text-gray-500">ID: {{ row.user.id }}</div>
                <div class="text-xs text-gray-500">
                  电话: {{ row.user.phone }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="服务信息" min-width="200">
          <template #default="{ row }">
            <div class="space-y-1">
              <div class="text-sm">
                <span class="text-gray-500">路线名称：</span>
                <span>{{ row.booking.routeName || "自定义行程" }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">服务日期：</span>
                <span>{{ row.booking.guideDate }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">开始时间：</span>
                <span>{{ row.booking.guideTime }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="退款详情" min-width="200">
          <template #default="{ row }">
            <div class="space-y-1">
              <div class="text-sm">
                <span class="text-gray-500">订单金额：</span>
                <span class="font-medium"
                  >¥{{ row.orderAmount.toFixed(2) }}</span
                >
              </div>
              <div class="text-sm">
                <span class="text-gray-500">申请退款：</span>
                <span class="font-medium text-red-500"
                  >¥{{ row.refundAmount.toFixed(2) }}</span
                >
              </div>
              <div class="text-sm">
                <span class="text-gray-500">退款原因：</span>
                <span>{{ row.reason }}</span>
              </div>
              <div
                class="text-sm"
                v-if="row.status === 'approved' || row.status === 'refunded'"
              >
                <span class="text-gray-500">实际退款：</span>
                <span class="font-medium text-red-500"
                  >¥{{ row.actualRefund.toFixed(2) }}</span
                >
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="处理信息" min-width="200">
          <template #default="{ row }">
            <div v-if="row.status === 'pending'" class="text-sm text-warning">
              等待处理
            </div>
            <div v-else class="space-y-1">
              <div class="text-sm">
                <span class="text-gray-500">处理人：</span>
                <span>{{ row.handler }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">处理时间：</span>
                <span>{{ formatDateTime(row.handleTime) }}</span>
              </div>
              <div class="text-sm" v-if="row.comment">
                <span class="text-gray-500">处理说明：</span>
                <span>{{ row.comment }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{ row }">
            <div class="flex flex-col space-y-1 items-end">
              <el-button
                size="small"
                class="op-btn"
                @click="handleViewDetail(row)"
                >查看详情</el-button
              >

              <template v-if="row.status === 'pending'">
                <el-button
                  size="small"
                  type="success"
                  class="op-btn"
                  @click="handleApprove(row)"
                  >通过退款</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  class="op-btn"
                  @click="handleReject(row)"
                  >拒绝退款</el-button
                >
              </template>

              <el-button
                v-if="row.status === 'approved'"
                size="small"
                type="primary"
                class="op-btn"
                @click="handleConfirmRefund(row)"
                >确认退款</el-button
              >
            </div>
          </template>
        </el-table-column>
        
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无退款申请" 
              :image-size="200"
            >
              <div class="empty-text">当前没有任何需要处理的退款申请</div>
              <div class="empty-subtext">用户提交退款申请后会在此处显示</div>
            </el-empty>
          </div>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 退款处理对话框 -->
    <el-dialog
      v-model="refundDialogVisible"
      :title="dialogTitle"
      width="500px"
      destroy-on-close
    >
      <div v-if="currentRefund" class="space-y-4">
        <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
          <div class="text-sm mb-2">
            <span class="text-gray-500">退款单号：</span>
            <span class="font-medium">{{ currentRefund.refundNo }}</span>
          </div>
          <div class="text-sm mb-2">
            <span class="text-gray-500">订单号：</span>
            <span class="font-medium">{{ currentRefund.orderNo }}</span>
          </div>
          <div class="text-sm mb-2">
            <span class="text-gray-500">申请退款：</span>
            <span class="font-medium text-red-500"
              >¥{{ currentRefund.refundAmount.toFixed(2) }}</span
            >
          </div>
          <div class="text-sm">
            <span class="text-gray-500">退款原因：</span>
            <span>{{ currentRefund.reason }}</span>
          </div>
        </div>

        <el-form :model="refundForm" label-width="100px">
          <el-form-item v-if="dialogAction === 'approve'" label="退款金额">
            <el-input-number
              v-model="refundForm.amount"
              :min="0"
              :max="currentRefund?.orderAmount || 0"
              :precision="2"
              :step="10"
              class="!w-full"
            />
          </el-form-item>
          <el-form-item label="处理说明">
            <el-input
              v-model="refundForm.comment"
              type="textarea"
              rows="3"
              placeholder="请输入处理说明"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRefundAction"
            >确认</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 退款详情模态框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="退款详情"
      width="800px"
      destroy-on-close
      append-to-body
      :before-close="handleCloseDetailDialog"
      @open="handleOpenDetailDialog"
      @close="enableBodyScroll"
      class="refund-detail-dialog"
      :modal-class="'refund-detail-modal'"
      :align-center="true"
      custom-class="custom-detail-dialog"
    >
      <div
        v-if="currentRefund"
        class="refund-detail-wrapper"
        ref="refundDetailWrapper"
      >
        <div class="refund-header">
          <div
            class="flex justify-between items-center pb-4 border-b dark:border-gray-700"
          >
            <div>
              <h3 class="text-xl font-bold">
                退款单号：{{ currentRefund.refundNo }}
              </h3>
              <div class="text-sm text-gray-500 mt-1">
                订单号：{{ currentRefund.orderNo }}
              </div>
              <div class="text-sm text-gray-500">
                申请时间：{{ formatDateTime(currentRefund.applyTime) }}
              </div>
            </div>
            <el-tag :type="getStatusType(currentRefund.status)" size="large">
              {{ getStatusText(currentRefund.status) }}
            </el-tag>
          </div>
        </div>

        <div class="refund-detail-scrollable" ref="refundScrollableContent">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
            <!-- 导游信息 -->
            <div class="card">
              <h4 class="card-title">导游信息</h4>
              <div class="flex items-center space-x-4 mb-4">
                <el-avatar :size="60" :src="currentRefund.guide.avatar" />
                <div>
                  <div class="text-lg font-medium">
                    {{ currentRefund.guide.name }}
                  </div>
                  <div class="text-sm text-gray-500">
                    ID: {{ currentRefund.guide.id }}
                  </div>
                  <div class="text-sm text-gray-500">
                    联系电话: {{ currentRefund.guide.phone }}
                  </div>
                </div>
              </div>
            </div>

            <!-- 用户信息 -->
            <div class="card">
              <h4 class="card-title">用户信息</h4>
              <div class="flex items-center space-x-4 mb-4">
                <el-avatar :size="60" :src="currentRefund.user.avatar" />
                <div>
                  <div class="text-lg font-medium">
                    {{ currentRefund.user.name }}
                  </div>
                  <div class="text-sm text-gray-500">
                    ID: {{ currentRefund.user.id }}
                  </div>
                  <div class="text-sm text-gray-500">
                    联系电话: {{ currentRefund.user.phone }}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 服务信息 -->
          <div class="card mt-6">
            <h4 class="card-title">服务信息</h4>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div class="text-sm">
                <span class="text-gray-500">路线名称：</span>
                <span>{{
                  currentRefund.booking.routeName || "自定义行程"
                }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">服务日期：</span>
                <span>{{ currentRefund.booking.guideDate }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">开始时间：</span>
                <span>{{ currentRefund.booking.guideTime }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">预定人数：</span>
                <span>{{ currentRefund.booking.people || "未知" }}人</span>
              </div>
            </div>
            <div class="mt-4" v-if="currentRefund.booking.specialRequests">
              <div class="text-sm text-gray-500">特殊要求：</div>
              <div class="mt-1 p-3 bg-gray-50 dark:bg-gray-700 rounded">
                {{ currentRefund.booking.specialRequests }}
              </div>
            </div>
          </div>

          <!-- 退款详情 -->
          <div class="card mt-6">
            <h4 class="card-title">退款详情</h4>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div class="text-sm">
                <span class="text-gray-500">订单金额：</span>
                <span class="font-medium"
                  >¥{{ currentRefund.orderAmount.toFixed(2) }}</span
                >
              </div>
              <div class="text-sm">
                <span class="text-gray-500">支付方式：</span>
                <span>{{ getPaymentMethod(currentRefund.paymentMethod) }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">申请退款：</span>
                <span class="font-medium text-red-500"
                  >¥{{ currentRefund.refundAmount.toFixed(2) }}</span
                >
              </div>
              <div
                class="text-sm"
                v-if="
                  currentRefund.status === 'approved' ||
                  currentRefund.status === 'refunded'
                "
              >
                <span class="text-gray-500">实际退款：</span>
                <span class="font-medium text-red-500"
                  >¥{{ currentRefund.actualRefund.toFixed(2) }}</span
                >
              </div>
            </div>

            <!-- 退款原因详情 -->
            <el-divider content-position="left">退款原因</el-divider>
            <div class="space-y-3">
              <div class="text-sm">
                <span class="text-gray-500">退款类型：</span>
                <el-tag
                  size="small"
                  :type="getRefundTypeTag(currentRefund.refundType)"
                >
                  {{ getRefundTypeText(currentRefund.refundType) }}
                </el-tag>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">退款原因：</span>
                <span>{{ currentRefund.reason }}</span>
              </div>
              <div v-if="currentRefund.reasonDetail" class="mt-2">
                <div class="text-sm text-gray-500 mb-1">详细说明：</div>
                <div class="p-3 bg-gray-50 dark:bg-gray-700 rounded text-sm">
                  {{ currentRefund.reasonDetail }}
                </div>
              </div>

              <div
                v-if="
                  currentRefund.evidenceImages &&
                  currentRefund.evidenceImages.length > 0
                "
                class="mt-3"
              >
                <div class="text-sm text-gray-500 mb-2">证据图片：</div>
                <div class="flex flex-wrap gap-2">
                  <div
                    v-for="(img, index) in currentRefund.evidenceImages"
                    :key="index"
                    class="relative"
                  >
                    <el-image
                      :src="img"
                      fit="cover"
                      class="w-20 h-20 rounded cursor-pointer"
                      @click="
                        handlePreviewImage(currentRefund.evidenceImages, index)
                      "
                    >
                      <template #error>
                        <div class="image-error">
                          <el-icon><Picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 处理信息 -->
          <div class="card mt-6" v-if="currentRefund.status !== 'pending'">
            <h4 class="card-title">处理信息</h4>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div class="text-sm">
                <span class="text-gray-500">处理人：</span>
                <span>{{ currentRefund.handler }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">处理时间：</span>
                <span>{{ formatDateTime(currentRefund.handleTime) }}</span>
              </div>
            </div>
            <div class="text-sm mt-3" v-if="currentRefund.comment">
              <span class="text-gray-500">处理说明：</span>
              <div class="mt-1 p-3 bg-gray-50 dark:bg-gray-700 rounded">
                {{ currentRefund.comment }}
              </div>
            </div>
          </div>

          <!-- 仲裁信息 -->
          <div class="card mt-6" v-if="currentRefund.hasArbitration">
            <h4 class="card-title">仲裁信息</h4>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div class="text-sm">
                <span class="text-gray-500">仲裁状态：</span>
                <el-tag
                  :type="
                    getArbitrationStatusType(currentRefund.arbitration.status)
                  "
                >
                  {{
                    getArbitrationStatusText(currentRefund.arbitration.status)
                  }}
                </el-tag>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">仲裁时间：</span>
                <span>{{
                  formatDateTime(currentRefund.arbitration.time)
                }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">仲裁员：</span>
                <span>{{ currentRefund.arbitration.arbitrator }}</span>
              </div>
              <div
                class="text-sm"
                v-if="currentRefund.arbitration.status === 'completed'"
              >
                <span class="text-gray-500">仲裁结果：</span>
                <span
                  :class="{
                    'text-success-500':
                      currentRefund.arbitration.result === 'approved',
                    'text-danger-500':
                      currentRefund.arbitration.result === 'rejected',
                  }"
                >
                  {{
                    getArbitrationResultText(currentRefund.arbitration.result)
                  }}
                </span>
              </div>
            </div>
            <div class="text-sm mt-3" v-if="currentRefund.arbitration.comment">
              <span class="text-gray-500">仲裁说明：</span>
              <div class="mt-1 p-3 bg-gray-50 dark:bg-gray-700 rounded">
                {{ currentRefund.arbitration.comment }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="refund-footer-btns">
          <template v-if="currentRefund && currentRefund.status === 'pending'">
            <el-button
              type="success"
              class="fixed-width-btn"
              @click="handleApprove(currentRefund)"
              >通过退款</el-button
            >
            <el-button
              type="danger"
              class="fixed-width-btn"
              @click="handleReject(currentRefund)"
              >拒绝退款</el-button
            >
          </template>
          <el-button
            v-if="currentRefund && currentRefund.status === 'approved'"
            type="primary"
            class="fixed-width-btn"
            @click="handleConfirmRefund(currentRefund)"
            >确认退款</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 仲裁对话框 -->
    <el-dialog
      v-model="arbitrationDialogVisible"
      title="仲裁处理"
      width="500px"
      destroy-on-close
    >
      <div v-if="currentRefund" class="space-y-4">
        <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
          <div class="text-sm mb-2">
            <span class="text-gray-500">退款单号：</span>
            <span class="font-medium">{{ currentRefund.refundNo }}</span>
          </div>
          <div class="text-sm mb-2">
            <span class="text-gray-500">订单号：</span>
            <span class="font-medium">{{ currentRefund.orderNo }}</span>
          </div>
          <div class="text-sm mb-2">
            <span class="text-gray-500">申请退款：</span>
            <span class="font-medium text-red-500"
              >¥{{ currentRefund.refundAmount.toFixed(2) }}</span
            >
          </div>
          <div class="text-sm">
            <span class="text-gray-500">退款原因：</span>
            <span>{{ currentRefund.reason }}</span>
          </div>
        </div>

        <el-form :model="arbitrationForm" label-width="100px">
          <el-form-item label="仲裁结果">
            <el-select
              v-model="arbitrationForm.result"
              placeholder="请选择仲裁结果"
              class="w-full"
            >
              <el-option label="同意退款" value="approved" />
              <el-option label="部分退款" value="partial" />
              <el-option label="拒绝退款" value="rejected" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="arbitrationForm.result === 'partial'"
            label="退款金额"
          >
            <el-input-number
              v-model="arbitrationForm.amount"
              :min="0"
              :max="currentRefund?.orderAmount || 0"
              :precision="2"
              :step="10"
              class="!w-full"
            />
          </el-form-item>
          <el-form-item label="仲裁原因">
            <el-input
              v-model="arbitrationForm.reason"
              type="textarea"
              rows="3"
              placeholder="请输入仲裁原因"
            />
          </el-form-item>
          <el-form-item label="仲裁说明">
            <el-input
              v-model="arbitrationForm.comment"
              type="textarea"
              rows="3"
              placeholder="请输入仲裁说明"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="arbitrationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmArbitration">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Download, Picture } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import * as XLSX from 'xlsx';
import axios from '@/api/axios';

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const activeTab = ref("pending");

// 从路由获取退款ID（如果有）
const refundId = computed(() => route.query.refundId);

// 搜索表单
const searchForm = reactive({
  keyword: "",
  status: "",
  dateRange: [],
});

// 各标签页数量统计
const tabCounts = reactive({
  pending: 0,
  approved: 0,
  rejected: 0,
  refunded: 0,
});

// 模拟退款数据（备用）
const mockRefundsList = [
  {
    id: 1,
    refundNo: "RF202401001",
    orderNo: "GD202401004",
    status: "pending",
    applyTime: "2024-01-12 15:30:00",
    guide: {
      id: 1,
      name: "李明",
      avatar: "/images/guides/guide1.jpg",
      phone: "13800138000"
    },
    user: {
      id: 104,
      name: "赵女士",
      avatar: "/images/users/user4.jpg",
      phone: "13300133000"
    },
    booking: {
      routeName: "自定义行程",
      guideDate: "2024-01-18",
      guideTime: "09:30"
    },
    orderAmount: 380,
    refundAmount: 380,
    reason: "临时有事无法出行",
    evidence: [
      "/images/refunds/evidence1.jpg"
    ]
  },
  {
    id: 2,
    refundNo: "RF202401002",
    orderNo: "GD202401006",
    status: "approved",
    applyTime: "2024-01-14 10:20:00",
    guide: {
      id: 2,
      name: "张华",
      avatar: "/images/guides/guide2.jpg",
      phone: "13700137000"
    },
    user: {
      id: 106,
      name: "吴先生",
      avatar: "/images/users/user6.jpg",
      phone: "13100131000"
    },
    booking: {
      routeName: "贵港文化遗产游",
      guideDate: "2024-01-20",
      guideTime: "10:00"
    },
    orderAmount: 450,
    refundAmount: 450,
    actualRefund: 450,
    reason: "天气原因，景点关闭",
    handler: "管理员A",
    handleTime: "2024-01-14 15:30:00",
    comment: "经核实，确实因天气原因景点关闭，同意全额退款"
  },
  {
    id: 3,
    refundNo: "RF202401003",
    orderNo: "GD202401007",
    status: "rejected",
    applyTime: "2024-01-15 14:40:00",
    guide: {
      id: 3,
      name: "王丽",
      avatar: "/images/guides/guide3.jpg",
      phone: "13500135000"
    },
    user: {
      id: 107,
      name: "郑先生",
      avatar: "/images/users/user7.jpg",
      phone: "13000130000"
    },
    booking: {
      routeName: "贵港美食文化游",
      guideDate: "2024-01-16",
      guideTime: "09:00"
    },
    orderAmount: 320,
    refundAmount: 320,
    reason: "对路线不满意，想换其他路线",
    handler: "管理员B",
    handleTime: "2024-01-15 16:20:00",
    comment: "服务已经开始，且导游已到达指定地点，不符合退款条件"
  },
  {
    id: 4,
    refundNo: "RF202401004",
    orderNo: "GD202401008",
    status: "refunded",
    applyTime: "2024-01-16 09:15:00",
    guide: {
      id: 1,
      name: "李明",
      avatar: "/images/guides/guide1.jpg",
      phone: "13800138000"
    },
    user: {
      id: 108,
      name: "陈女士",
      avatar: "/images/users/user8.jpg",
      phone: "13200132000"
    },
    booking: {
      routeName: "贵港一日游",
      guideDate: "2024-01-25",
      guideTime: "08:30"
    },
    orderAmount: 380,
    refundAmount: 380,
    actualRefund: 342, // 扣除手续费
    reason: "行程计划变更",
    handler: "管理员A",
    handleTime: "2024-01-16 11:30:00",
    refundTime: "2024-01-16 14:25:00",
    comment: "符合提前7天取消政策，扣除10%手续费"
  }
];

const refundsList = ref([]);

// 格式化日期时间
const formatDateTime = (date) => {
  return date ? dayjs(date).format("YYYY-MM-DD HH:mm:ss") : '';
};

// 获取状态显示文本
const getStatusText = (status) => {
  const statusMap = {
    pending: "待处理",
    approved: "已通过",
    rejected: "已拒绝",
    refunded: "已退款"
  };
  return statusMap[status] || status;
};

// 获取状态对应的类型
const getStatusType = (status) => {
  const typeMap = {
    pending: "warning",
    approved: "success",
    rejected: "danger",
    refunded: "info"
  };
  return typeMap[status] || "info";
};

// 获取退款列表
const getRefundsList = async () => {
  loading.value = true;
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      status: activeTab.value !== 'all' ? activeTab.value : undefined,
      ...searchForm
    };
    
    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0];
      params.endDate = searchForm.dateRange[1];
      delete params.dateRange;
    }
    
    // 如果有指定的退款单号，添加到参数
    if (refundId.value) {
      params.refundId = refundId.value;
    }
    
    const response = await axios.get('/admin/guides/refunds', { params });
    
    if (response && response.code === 200 && response.data) {
      refundsList.value = response.data.list || [];
      total.value = response.data.total || 0;
      
      // 更新各标签页数量
      if (response.data.counts) {
        Object.keys(tabCounts).forEach(key => {
          tabCounts[key] = response.data.counts[key] || 0;
        });
      }
    } else {
      // 使用模拟数据
      let filteredRefunds = [...mockRefundsList];
      
      // 按标签筛选
      if (activeTab.value !== 'all' && activeTab.value !== '') {
        filteredRefunds = filteredRefunds.filter(item => item.status === activeTab.value);
      }
      
      // 按退款单号筛选
      if (refundId.value) {
        filteredRefunds = filteredRefunds.filter(item => 
          item.refundNo === refundId.value || item.orderNo === refundId.value
        );
      }
      
      // 按关键词筛选
      if (searchForm.keyword) {
        const keyword = searchForm.keyword.toLowerCase();
        filteredRefunds = filteredRefunds.filter(item => 
          item.refundNo.toLowerCase().includes(keyword) || 
          item.orderNo.toLowerCase().includes(keyword) || 
          item.guide.name.toLowerCase().includes(keyword) || 
          item.user.name.toLowerCase().includes(keyword)
        );
      }
      
      refundsList.value = filteredRefunds;
      total.value = filteredRefunds.length;
      
      // 统计各状态数量
      const counts = mockRefundsList.reduce((acc, curr) => {
        acc[curr.status] = (acc[curr.status] || 0) + 1;
        return acc;
      }, {});
      
      // 更新标签页数量
      Object.keys(tabCounts).forEach(key => {
        tabCounts[key] = counts[key] || 0;
      });
    }
  } catch (error) {
    console.error("获取退款列表失败:", error);
    ElMessage.error("获取退款列表失败，使用测试数据");
    
    // 使用模拟数据
    let filteredRefunds = [...mockRefundsList];
    
    // 按标签筛选
    if (activeTab.value !== 'all' && activeTab.value !== '') {
      filteredRefunds = filteredRefunds.filter(item => item.status === activeTab.value);
    }
    
    // 按退款单号筛选
    if (refundId.value) {
      filteredRefunds = filteredRefunds.filter(item => 
        item.refundNo === refundId.value || item.orderNo === refundId.value
      );
    }
    
    refundsList.value = filteredRefunds;
    total.value = filteredRefunds.length;
    
    // 统计各状态数量
    const counts = mockRefundsList.reduce((acc, curr) => {
      acc[curr.status] = (acc[curr.status] || 0) + 1;
      return acc;
    }, {});
    
    // 更新标签页数量
    Object.keys(tabCounts).forEach(key => {
      tabCounts[key] = counts[key] || 0;
    });
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  page.value = 1;
  getRefundsList();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  searchForm.dateRange = [];
  page.value = 1;
  getRefundsList();
};

// 标签页切换
const handleTabChange = () => {
  page.value = 1;
  getRefundsList();
};

// 查看详情
const handleViewDetail = (row) => {
  currentRefund.value = row;
  detailDialogVisible.value = true;
};

// 审核通过退款
const handleApprove = async (row) => {
  currentRefund.value = row;
  approveDialogVisible.value = true;
  approveForm.refundId = row.id;
  approveForm.orderNo = row.orderNo;
  approveForm.requestAmount = row.refundAmount;
  approveForm.actualAmount = row.refundAmount; // 默认全额退款
  approveForm.comment = "";
};

// 提交审核通过
const handleApproveSubmit = async () => {
  if (approveForm.actualAmount <= 0) {
    ElMessage.warning("请输入有效的退款金额");
    return;
  }

  try {
    await axios.put(`/admin/guides/refunds/${approveForm.refundId}/approve`, {
      actualRefund: approveForm.actualAmount,
      comment: approveForm.comment,
      handler: localStorage.getItem('adminName') || '管理员',
      handleTime: new Date()
    });
    
    ElMessage.success("退款申请已通过");
    approveDialogVisible.value = false;
    getRefundsList();
  } catch (error) {
    console.error("审核通过失败:", error);
    ElMessage.error("审核通过失败");
  }
};

// 拒绝退款
const handleReject = async (row) => {
  currentRefund.value = row;
  rejectDialogVisible.value = true;
  rejectForm.refundId = row.id;
  rejectForm.orderNo = row.orderNo;
  rejectForm.reason = "";
};

// 提交拒绝
const handleRejectSubmit = async () => {
  if (!rejectForm.reason.trim()) {
    ElMessage.warning("请输入拒绝理由");
    return;
  }

  try {
    await axios.put(`/admin/guides/refunds/${rejectForm.refundId}/reject`, {
      comment: rejectForm.reason,
      handler: localStorage.getItem('adminName') || '管理员',
      handleTime: new Date()
    });
    
    ElMessage.success("退款申请已拒绝");
    rejectDialogVisible.value = false;
    getRefundsList();
  } catch (error) {
    console.error("拒绝退款失败:", error);
    ElMessage.error("拒绝退款失败");
  }
};

// 确认退款完成
const handleConfirmRefunded = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确认退款已完成处理吗？订单号: ${row.orderNo}`,
      "确认退款完成",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success",
      }
    );

    try {
      await axios.put(`/admin/guides/refunds/${row.id}/complete`, {
        refundTime: new Date()
      });
      
      ElMessage.success("退款已完成");
      getRefundsList();
    } catch (error) {
      console.error("确认退款完成失败:", error);
      ElMessage.error("确认退款完成失败");
    }
  } catch (error) {
    if (error === "cancel") return;
  }
};

// 导出数据
const handleExport = () => {
  // 准备导出数据
  const exportData = refundsList.value.map(item => ({
    退款单号: item.refundNo,
    订单号: item.orderNo,
    申请时间: formatDateTime(item.applyTime),
    退款状态: getStatusText(item.status),
    导游ID: item.guide.id,
    导游姓名: item.guide.name,
    导游电话: item.guide.phone,
    用户ID: item.user.id,
    用户姓名: item.user.name,
    用户电话: item.user.phone,
    路线名称: item.booking.routeName || "自定义行程",
    服务日期: item.booking.guideDate,
    开始时间: item.booking.guideTime,
    订单金额: `¥${item.orderAmount.toFixed(2)}`,
    申请退款: `¥${item.refundAmount.toFixed(2)}`,
    实际退款: item.actualRefund ? `¥${item.actualRefund.toFixed(2)}` : '-',
    退款原因: item.reason || '-',
    处理人: item.handler || '-',
    处理时间: item.handleTime ? formatDateTime(item.handleTime) : '-',
    退款时间: item.refundTime ? formatDateTime(item.refundTime) : '-',
    处理说明: item.comment || '-'
  }));

  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.json_to_sheet(exportData);
  
  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, '导游退款仲裁');
  
  // 导出Excel文件
  XLSX.writeFile(workbook, `导游退款仲裁_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`);
  
  ElMessage.success("退款仲裁数据导出成功");
};

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val;
  getRefundsList();
};

const handleCurrentChange = (val) => {
  page.value = val;
  getRefundsList();
};

// 详情对话框相关
const detailDialogVisible = ref(false);
const currentRefund = ref(null);

// 审核通过对话框
const approveDialogVisible = ref(false);
const approveForm = reactive({
  refundId: null,
  orderNo: "",
  requestAmount: 0,
  actualAmount: 0,
  comment: ""
});

// 拒绝对话框
const rejectDialogVisible = ref(false);
const rejectForm = reactive({
  refundId: null,
  orderNo: "",
  reason: ""
});

// 预览图片相关
const previewImages = ref([]);
const previewIndex = ref(0);
const previewVisible = ref(false);

// 预览图片
const handlePreviewImage = (images, index) => {
  previewImages.value = images;
  previewIndex.value = index;
  previewVisible.value = true;
};

// 关闭预览
const closePreview = () => {
  previewVisible.value = false;
};

// 返回
const goBack = () => {
  router.back();
};

// 页面加载时获取数据
onMounted(() => {
  getRefundsList();
});
</script>

<style lang="scss" scoped>
.guide-refunds-page {
  padding: 20px;

  :deep(.el-tabs__header) {
    margin-bottom: 20px;
  }

  :deep(.el-table) {
    --el-table-border-color: var(--el-border-color-lighter);
    --el-table-header-bg-color: var(--el-fill-color-light);

    .el-table__header th {
      font-weight: 600;
      color: var(--el-text-color-primary);
    }

    .dark & {
      --el-table-border-color: var(--el-border-color-darker);
      --el-table-header-bg-color: var(--el-bg-color-overlay);

      .el-table__header th {
        color: var(--el-text-color-primary);
      }
    }
  }

  .card {
    background-color: var(--el-bg-color-overlay);
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    border: 1px solid var(--el-border-color-lighter);

    .dark & {
      border-color: var(--el-border-color-darker);
    }
  }

  .card-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    color: var(--el-text-color-primary);

    .dark & {
      border-color: var(--el-border-color-darker);
    }
  }

  .dialog-scrollable {
    max-height: calc(80vh - 120px);
    overflow-y: auto;
    padding-right: 5px;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: var(--el-border-color);
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background-color: var(--el-fill-color-lighter);
      border-radius: 3px;
    }
  }

  :deep(.el-dialog__body) {
    padding-top: 16px;
    padding-bottom: 16px;
    max-height: 80vh;
  }

  // 表格操作按钮样式
  :deep(.el-button) {
    &.w-full {
      width: 100%;
      justify-content: center;
    }
  }
}

// 添加模态框样式
:deep(.refund-detail-dialog) {
  .el-overlay {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .custom-detail-dialog {
    height: auto !important;
    max-height: 80vh !important;
    margin: 15vh auto !important;
  }

  .refund-detail-wrapper {
    height: 500px;
    max-height: 500px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    position: relative;
  }

  .refund-header {
    padding: 0 20px;
    flex-shrink: 0;
  }

  .refund-detail-scrollable {
    flex: 1;
    overflow-y: auto;
    padding: 0 20px 20px;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: var(--el-border-color);
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background-color: var(--el-fill-color-lighter);
      border-radius: 3px;
    }
  }

  .el-dialog__body {
    padding: 20px 0 0 0 !important;
    overflow: hidden !important;
  }

  .el-dialog__footer {
    padding: 10px 20px 20px;
    border-top: 1px solid var(--el-border-color-lighter);
  }

  .refund-footer-btns {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  .fixed-width-btn {
    min-width: 90px;
    padding-left: 15px;
    padding-right: 15px;
  }
}

.refund-detail-modal {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

// 修改操作按钮样式
.op-btn {
  width: 90px !important;
  margin-left: 0 !important;
  margin-right: 0 !important;
}

.empty-state {
  padding: 30px 0;
  max-height: 400px;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
